import type { Ref } from 'vue'
import type { NvSearchActions, NvSearchFormOption } from '@/crud/types'
import type { NvFormOption } from '@/form/types'
import type { NvLocale } from '@/utils/locale'
import { computed, ref, unref } from 'vue'
import { resolveVisible } from '@/utils'
import { provideCollapse } from '@/utils/collapse'

export function useCollapse(
  searchOption: Ref<NvFormOption>,
  originalSearchOption: Ref<NvSearchFormOption>,
  actions: Ref<NvSearchActions>,
  t: Ref<NvLocale>,
) {
  const collapsed = ref(false)

  let { collapsedRow, collapsedNum } = originalSearchOption.value

  if (typeof collapsedRow === 'number' || typeof collapsedNum === 'number') {
    collapsed.value = true
  }
  if (typeof collapsedRow !== 'number') {
    collapsedRow = Object.keys(searchOption.value.fields).length
  }
  const allowCollapse = collapsed.value
  provideCollapse({ collapsed, collapsedRow, collapsedNum })

  function collapseVisible(gridResponsiveRows: number) {
    const visible = resolveVisible(actions.value.collapseBtn, true)
    if (!visible) {
      return false
    }

    if (!allowCollapse)
      return false

    const { collapsedRow, collapsedNum } = originalSearchOption.value
    if (typeof collapsedRow === 'number' && collapsedRow < gridResponsiveRows) {
      return true
    }

    if (typeof collapsedNum === 'number' && collapsedNum < Object.keys(searchOption.value.fields).length) {
      return true
    }
    return false
  }

  const collapseContent = computed(() => {
    const collapseBtn = unref(actions.value.collapseBtn)
    if (!resolveVisible(collapseBtn, true)) {
      return false
    }
    if (typeof collapseBtn === 'object') {
      const content = collapseBtn.content
      if (content === false) {
        return false
      }
      if (typeof content === 'function') {
        return () => content(collapsed.value)
      }
    }
    return collapsed.value ? t.value.button.expand : t.value.button.collapse
  })

  return { collapsed, collapseVisible, collapseContent }
}
